
layui.use(['laydate', 'laypage', 'layer', 'table', 'carousel', 'upload', 'element'], function() {

    var background_state = 0;

    var laydate = layui.laydate //日期
        , laypage = layui.laypage //分页
        , layer = layui.layer //弹层
        , table = layui.table //表格
        , carousel = layui.carousel //轮播
        , upload = layui.upload //上传
        , $ = layui.jquery
        , element = layui.element; //元素操作

    var table_format_update = [[
                {checkbox: true}
                , {field: 'id', align: 'center', title: 'ID', width: 50}
                , {field: 'companyid', align: 'center', title: '公司ID', width: 80}
                , {field: 'companyname', align: 'center', title: '公司名称', width: 280}
                , {field: 'zcellname', align: 'center', title: 'zcell服务器名称', width: 160}
                , {field: 'nodename', align: 'center', title: 'node名称', width: 160}
                , {field: 'zcellip', align: 'center', title: 'zcell外网IP', width: 200}
                , {fixed: 'right',width: 160, align: 'center', toolbar: '#upbarDemo'}
            ]];


    $('.layui-table').each(function() {
        //获取标签对于的一个属性
        var $obj = $(this);
        var tableid = $obj[0].id;
        var etaleid = '#' + tableid;
        var toolid = 'tool(' + tableid + ')';
        //var tableid = document.getElementById('update').id;
        console.log(tableid);
        createtable(etaleid,tableid,update_data,table_format_update,toolid);
        updatetool(toolid, tableid);
    });
    console.log(update_data);
    // var id_node = {};
    // for (var i = 0; i<update_data.length; i++){
    //     id_node[update_data[i]["companyid"]] = i
    // }

    //执行渲染
    function createtable(etaleid,tableid,datas,table_format,toolid) {
        var uptable = table.render({
            elem: etaleid,
            id: tableid,
            //url: '/demo/table/user/',
            limit:10,
            page: true,
            // stateSave: true, //是否打开客户端状态记录功能,此功能在ajax刷新纪录的时候不会将个性化设定回复为初始化状态
            // processing: true, //DataTables载入数据时，是否显示‘进度’提示
            // scrollCollapse: true, //是否开启DataTables的高度自适应，当数据条数不够分页数据条数的时候，插件高度是否随数据条数而改变
            // searching: true, //是否允许Datatables开启本地搜索
            data:datas,
            cols:table_format
        });
        // if (tableid === 'update') {
        active = {
            getCheckLength: function () {
                var checkStatus = table.checkStatus(tableid);
                var data = checkStatus.data;
                layer.msg('选中了：' + data.length + ' 个');
            },
            reloads: function(){
                var demoReload = $('#demoReload');
                console.log(demoReload.val());
                 $.ajax({
                    url: "/updateselect/",
                    dataType: 'json',
                    type: 'POST',
                    data: {"companyname": demoReload.val()},
                    success: function (new_data) {
                        console.log(new_data["zcell_new_up"]);
                        uptable.reload({
                            data: new_data["zcell_new_up"]
                        })
                    }
                })
            },
            Deployment: function () {
                //配置一个透明的询问框
                var data = "";
                layer.msg('将对所有zecell进行更新，请确认更新文件是否已经放置到位！', {
                    time: 20000,
                    //20s后自动关闭
                    btn: ['更新', '取消'],
                    success: function (layero) {
                        var btn = layero.find('.layui-layer-btn');
                        var btntrue = layero.find('.layui-layer-btn0');
                        btn.css('text-align', 'center');
                        btntrue.on('click', function () {
                            if (background_state === 0) {
                                ajaxsend(data,0)
                            }else {
                                layer.msg('更新程序正在执行，请稍后！！！');
                            }
                        })
                    }
                });
            },
            Update: function () {
                //示范一个公告层
                var checkStatus = table.checkStatus('update');
                var data = checkStatus.data;
                console.log(data);
                if (data.length === 0) {
                    layer.msg('没有选中数据');
                } else {
                    layer.open({
                        type: 1,
                        title: false, //不显示标题栏
                        closeBtn: false,
                        area: '300px;',
                        shade: 0.8,
                        maxHeight: 500,
                        id: 'LAY_layuipro', //设定一个id，防止重复弹出
                        btn: ['确认更新', '返回修改'],
                        moveType: 1, //拖拽模式，0或者1
                        content: updatelist(data),
                        success: function (layero) {
                            var btn = layero.find('.layui-layer-btn');
                            var btntrue = layero.find('.layui-layer-btn0');
                            btn.css('text-align', 'center');
                            btntrue.on('click', function () {
                                if (background_state === 0) {
                                    ajaxsend(data,1)
                                }else {
                                    layer.msg('更新程序正在执行，请稍后！！！');
                                }
                            })
                        }
                    });
                }
            }
        };
        }
    // }

    // $('#searchnode').on('click', function () {
    //     var demoReload = $('#demoReload');
    //     console.log(demoReload.val());
    //     console.log(update_data);
    //     uptable.reload({
    //         data:update_data
    //         // where: {
    //         //     nodename:'JXV20100605'
    //         // }
    //     });
    // });

    function updatetool(toolid, tableid) {
        //监听工具条
        //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        table.on(toolid, function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            var checkStatus = table.checkStatus(tableid);
            console.log(data);
            if (layEvent === 'updatenu') {
                layer.msg('更新操作');
                if (background_state === 0) {
                    ajaxsend(data,1)
                }else {
                    layer.msg('更新程序正在执行，请稍后！！！');
                }
            }
        });
    }


    function updatelist(updatedata) {
        var contxt = '<div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300; text-align:center">';
        for (var i = 0; i <= updatedata.length; i++) {
            if (i === updatedata.length) {
                contxt = contxt + '</div>'
            } else {
                contxt = contxt + updatedata[i]["zcellname"] + ' : ' + updatedata[i]["nodename"] + '<br>'
            }
        }
        return contxt
    }
    
    function ajaxsend(update_json, status) {
        background_state = 1;
        if (status === 0) {
            console.log('全部更新');
            $.ajax({
                url: "/updatesend/",
                dataType: 'json',
                type: 'POST',
                data: {"status": 1},
                success: function (returnupdata) {
                    console.log(returnupdata);
                    background_state = 0;
                    layer.msg(returnupdata["status"], {
                        time: 20000,
                        //20s后自动关闭
                        btn: ['更新', '取消'],
                        success: function (layero) {
                            var btn = layero.find('.layui-layer-btn');
                            var btntrue = layero.find('.layui-layer-btn0');
                            btn.css('text-align', 'center');
                        }
                    })
                }
            })
        }else{
            $.ajax({
                url: "/updatesend/",
                dataType: 'json',
                type: 'POST',
                data: {"data": JSON.stringify(update_json), "status": 2},
                success: function (returnupdata) {
                    console.log(returnupdata);
                    background_state = 0;
                    layer.msg(returnupdata["status"], {
                        time: 20000,
                        //20s后自动关闭
                        btn: ['确定'],
                        success: function (layero) {
                            var btn = layero.find('.layui-layer-btn');
                            var btntrue = layero.find('.layui-layer-btn0');
                            btn.css('text-align', 'center');
                        }
                    })
                }
            })
        }
    }

    $('.demoTable .layui-btn').on('click',
    function() {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
});